/**
 * Created by admin on 2016/8/11.
 */
var assert = require('../assert');
var co = require('co');
// 获取购物车
exports.getShoppingItem = function (req, res) {
    var userId = req.query.userId;
    if (!userId){
        res.send(assert.response_sms(400, '参数错误'));
        return
    }
    var User = Parse.Object.extend('User');
    var user = new User();
    user.id = userId;
    var query = new Parse.Query('OPShoppingItem');
    query.include('product');
    query.equalTo('user', user);
    query.select('id', 'product', 'count');
    query.find().then(function (shoppingItems) {
        var response_content = [];
        for (var i=0; i<shoppingItems.length; i++){
            var temp = {};
            temp['count'] = shoppingItems[i].get('count');
            var inner_product = shoppingItems[i].get('product');
            temp['product'] = assert.obj2dic(inner_product,['id','title', 'country', 'images','salePrice']);
            if (temp['product']['images'].length>0){
                temp['product']['images'] = temp['product']['images'][0]
            }
            temp['objectId'] = shoppingItems[i].id;
            response_content.push(temp);
        }
        res.send(assert.response_sms(200, '获取购物车成功', response_content));
    }, function (error) {
        res.send(assert.response_sms(400, '获取购物车失败' + error.message));
    });
};
// 修改购物车
exports.putShoppingItem = function (req, res) {
    // 获取参数，判断参数合法性
    var shoppingItem = req.params.shoppingItemId;
    var count = req.body.count;
    count = parseInt(count);
    if (!(shoppingItem && count)){
        res.send(assert.response_sms(400, '参数错误'));
        return
    }
    // 执行查询
    var query = new Parse.Query('OPShoppingItem');
    query.get(shoppingItem).then(function (shoppingItem) {
        shoppingItem.increment('count', count);
        return shoppingItem.save();
    }, function (error) {
        res.send(assert.response_sms(400, '获取购物车失败' + error.message));
    }).then(function (result) {
        res.send(assert.response_sms(200, '修改购物车成功', result));
    }, function (error) {
        res.send(assert.response_sms(400, '修改购物车失败' + error.message));
    });
};
// 添加一个商品到购物车
exports.postShoppingItem = function (req, res) {
    // 获取参数
    var userId = req.query.userId;
    var productId = req.body.productId;
    var count = req.body.count;
    try {
        count = parseInt(count)
    }catch (error){
        count=1;
    }
    if (!(userId && productId && count)){
        res.send(assert.response_sms(400, '提交的商品参数有错'));
        return
    }
    // 创建product，user对象
    var Product = Parse.Object.extend('OPProduct');
    var product = new Product;
    product.id = productId;
    var User = Parse.Object.extend('User');
    var user = new User();
    user.id = userId;
    // 先查询购物车里是否已经有这件商品了
    var query = new Parse.Query('OPShoppingItem');
    query.equalTo('user', user);
    query.equalTo('product', product);
    query.find().then(function (result) {
        // 如果之前添加过这个商品就增加数量，如果没有就直接插入
        if (result.length>0){
            var pro_count = result[0].get('count');
            result[0].set('count', pro_count+count);
            result[0].save().then(function (result) {
                res.send(assert.response_sms(200, '添加成功',{increment:false}));
            }, function (error) {
                res.send(assert.response_sms(400, '添加失败'));
                console.log(error);
            });
        }else {
            // 执行插入
            var ShoppingItem = Parse.Object.extend('OPShoppingItem');
            var shoppingItem = new ShoppingItem();
            shoppingItem.set('user', user);
            shoppingItem.set('product', product);
            shoppingItem.set('count', count);
            shoppingItem.save().then(function (shoppingItem) {
                res.send(assert.response_sms(200, '添加购物车成功',{increment:true}));
            }, function (error) {
                res.send(assert.response_sms(400, '添加购物车出错' + error.message));
            });
        }
    });
};
// 删除购物车
exports.deleteShoppingItem = function (req, res) {
    var shoppingItemId = req.params.shoppingItemId;
    if (!shoppingItemId){
        res.send(assert.response_sms(400, '参数有错'));
        return
    }
    // 查询购物车
    var query = new Parse.Query('OPShoppingItem');
    query.get(shoppingItemId).then(function (shoppingItem) {
        return shoppingItem.destroy();
    }, function (error) {
        res.send(assert.response_sms(400, '获取购物车出错' + error.message));
    }).then(function (result) {
        res.send(assert.response_sms(200, '删除购物车成功', result));
    }, function (error) {
        res.send(assert.response_sms(400, '删除购物车出错' + error.message));
    });
};
// 返回购物车数量
exports.getShoppingItemCount = function (req, res) {
    var userId = req.query.userId;
    if (!userId){
        res.send(assert.response_sms(401, 'userId为空'));
        return;
    }
    var User = Parse.Object.extend('User');
    var user = new User();
    user.id = userId;
    var query = new Parse.Query('OPShoppingItem');
    query.equalTo('user', user);
    query.count().then(function (count) {
        res.send(assert.response_sms(200, '返回数量成功', count));
    }, function (error) {
        res.send(assert.response_sms(400, '返回数量失败'));
        console.log(error.message);
    });
};
// *********************************************************************
exports.kdGetShoppingItem = function (req, res) {
    var userId = req.query.userId;
    if (!userId){
        res.json(assert.response_sms(400, '参数错误'));
        return
    }
    var User = Parse.Object.extend('User');
    var user = new User();
    user.id = userId;
    var query = new Parse.Query('KDShoppingItem');
    query.include('product.product', 'product.store');
    query.equalTo('user', user);
    query.select('product', 'count');
    query.find().then(function (shoppingItems) {

        var store_list = [];
        var response_content = {};
        Array.prototype.contains = function(element){
            return this.indexOf(element) > -1;
        };
        shoppingItems.forEach(function (item) {
            var store_name = item.get('product').get('store').get('name');
            if (!store_list.contains(store_name)){
                store_list.push(store_name);
                response_content[store_name] = [];
            }
            var temp = {};
            temp['count'] = item.get('count');
            var inner_product = item.get('product').get('product');
            temp['product'] = assert.obj2dic(inner_product,['title', 'country', 'images']);
            temp['product'].salePrice = item.get('product').get('salePrice');
            temp['product']['objectId'] = item.get('product').id;
            if (temp['product']['images'].length>0){
                temp['product']['images'] = temp['product']['images'][0]
            }
            temp['objectId'] = item.id;
            response_content[store_name].push(temp);
        });
        res.json(assert.con2json(200, '获取购物车成功', response_content));
    }, function (error) {
        res.json(assert.con2json(400, '获取购物车失败' + error.message));
    });
};
// 修改购物车
exports.kdPutShoppingItem = function (req, res) {
    // 获取参数，判断参数合法性
    var shoppingItem = req.params.shoppingItemId;
    var count = req.body.count;
    count = parseInt(count);
    if (!(shoppingItem && count)){
        res.send(assert.response_sms(400, '参数错误'));
        return
    }
    // 执行查询
    var query = new Parse.Query('KDShoppingItem');
    query.get(shoppingItem).then(function (shoppingItem) {
        shoppingItem.increment('count', count);
        return shoppingItem.save();
    }, function (error) {
        res.send(assert.response_sms(400, '获取购物车失败' + error.message));
    }).then(function (result) {
        res.send(assert.response_sms(200, '修改购物车成功', result));
    }, function (error) {
        res.send(assert.response_sms(400, '修改购物车失败' + error.message));
    });
};
// 添加一个商品到购物车
exports.kdCreateShoppingItem = function (req, res) {
    // 获取参数
    var userId = req.query.userId;
    var productId = req.body.productId;
    var count = req.body.count;
    try {
        count = parseInt(count)
    }catch (error){
        count=1;
    }
    if (!(userId && productId && count)){
        res.send(assert.response_sms(400, '提交的商品参数有错'));
        return
    }
    // 创建product，user对象
    var Product = Parse.Object.extend('OPStoreGoods');
    var product = new Product;
    product.id = productId;
    var User = Parse.Object.extend('User');
    var user = new User();
    user.id = userId;
    // 先查询购物车里是否已经有这件商品了
    var query = new Parse.Query('KDShoppingItem');
    query.equalTo('user', user);
    query.equalTo('product', product);
    query.find().then(function (result) {
        // 如果之前添加过这个商品就增加数量，如果没有就直接插入
        if (result.length>0){
            var pro_count = result[0].get('count');
            result[0].set('count', pro_count+count);
            result[0].save().then(function (result) {
                res.send(assert.response_sms(200, '添加成功',{increment:false}));
            }, function (error) {
                res.send(assert.response_sms(400, '添加失败'));
                console.log(error);
            });
        }else {
            // 执行插入
            var ShoppingItem = Parse.Object.extend('KDShoppingItem');
            var shoppingItem = new ShoppingItem();
            shoppingItem.set('user', user);
            shoppingItem.set('product', product);
            shoppingItem.set('count', count);
            shoppingItem.save().then(function (shoppingItem) {
                res.send(assert.response_sms(200, '添加购物车成功',{increment:true}));
            }, function (error) {
                res.send(assert.response_sms(400, '添加购物车出错' + error.message));
            });
        }
    });
};
// 删除购物车
exports.kdDeleteShoppingItem = function (req, res) {
    var shoppingItems = req.body.deleteObj;
    try {
        shoppingItems = JSON.parse(shoppingItems);
    }catch (error){
        res.json(assert.con2json(101, '参数错误'));
    }
    // 查询购物车
    var temp = [];
    shoppingItems.forEach(function (item) {
        var query = new Parse.Query('KDShoppingItem');
        query.get(item).then(function (shoppingItem) {
           temp.push(shoppingItem.destroy());
        }, function (error) {
           res.json(assert.con2json(102, '获取购物车出错' + error.message));
        });
    });
    Promise.all(temp).then(function (results) {
        res.json(assert.con2json(200, '获取购物成功'));
    }, function (error) {
        res.json(assert.con2json(400, '获取购物车出错' + error.message));
    });

};
// 返回购物车数量
exports.kdGetShoppingItemCount = function (req, res) {
    var userId = req.query.userId;
    if (!userId){
        res.send(assert.response_sms(401, 'userId为空'));
        return;
    }
    var User = Parse.Object.extend('User');
    var user = new User();
    user.id = userId;
    var query = new Parse.Query('KDShoppingItem');
    query.equalTo('user', user);
    query.count().then(function (count) {
        res.send(assert.response_sms(200, '返回数量成功', count));
    }, function (error) {
        res.send(assert.response_sms(400, '返回数量失败'));
        console.log(error.message);
    });
};